/**
 * Created by zlj on 2016/11/30.
 */
var $ = require('jquery');
require('layout/uiJs');
require('easyui');
var isSale = require('libs/user-type').isSale;
require(['uploadifive'],function () {
    $("#uploadifive").uploadifive(
        $.extend({},uploadifiveSettings,{
            uploadScript: 'api/v1/p/mms/logisticsChannelPlan/import',
            onUploadComplete : function(file, data) {
                var obj = JSON.parse(data);
                if(obj.code == 201){
                    window.location ="api/v1/p/crm/fileoper/download?id="+obj.data.id;
                }else if(obj.code ==200){
                    alert("导入成功!");
                }else{
                    alert(obj.message);
                }
            }
        })
    )
});
var $confirm = require('libs/confirm');
    tableinit();
    comboxInit('api/v1/p/mms/logistics/query',{},$("#logisticsId"));
    comboxInit('api/v1/p/mms/logisticsChannel/query',{}
        ,$("#channelId"));
    destInit();
    $('body').on('click',"a[name=detail]",function () {
        var rowDatas = $('#logistics_Plan_table').datagrid('getRows');
        var id = rowDatas[$(this).attr('row')].id;
        window.location.href = "Logistics-product-detail?id="+id;
    });

    $("#btn_search").on('click',function () {
        var d1 = $('#startDt').datebox('getValue');
        var d2 = $('#endDt').datebox('getValue');
        $('#logistics_Plan_table').datagrid('load',{
            logisticsId:$('#tb input[name=logisticsId]').val(),
            channelId:$('#tb input[name=channelId]').val(),
            toWarehouseId:$('#tb input[name=toWarehouseId]').val(),
            startPort:$('#tb input[name=startPort]').val(),
            starDate:d1?$('#startDt').data('utc0'):'',
            endDate:d2?$('#endDt').data('utc0'):''
        });
    });

    //修改
    $("body").on("click","a[name=edit]",function () {
        var rowDatas = $('#logistics_Plan_table').datagrid('getRows');
        var id = rowDatas[$(this).attr('row')].id;
        window.location.href = "Logistics-product-update?id="+id;
    });

    //删除
    $("body").on("click","a[name=delete]",function () {
        var rowDatas = $('#logistics_Plan_table').datagrid('getRows');
        var id = rowDatas[$(this).attr('row')].id;
        var url = 'api/v1/p/mms/logisticsChannelPlan/delete';
        optFun(url,{id:id});
    });
    //下载模板
    $('#exportTemp').on('click',function () {
        window.location.href='/upload/template/国际物流计划导入模板.xls'
    });

    //导出
    $("#plan_export").on("click",function () {
        var rows = $("#logistics_Plan_table").datagrid("getSelections");
        var $form;
        if (rows.length == 0){
            $confirm("确认导出所有数据吗？",function () {
                $form  = $("#serchForm");
                $form.attr("action" ,'api/v1/p/mms/logisticsChannelPlan/export')
                $form.submit();

            });
        }else{
            $confirm("确认导出选择行吗？",function () {
                var jsonString =installId(rows);
                console.info(jsonString);
                $form  = $("#serchForm");
                $form.find("input[name=jsonString]").val(JSON.stringify(jsonString));
                $form.attr("action" ,'api/v1/p/mms/logisticsChannelPlan/export')
                $form.submit();
                $form.find("input[name=jsonString]").val('');
            });
        }
    });
function editPlan(id) {
    window.location.href = "Logistics-product-update?id="+id;
}
function tableinit() {
    $("#logistics_Plan_table").datagrid({
        url:'api/v1/p/mms/logisticsChannelPlan/list',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        /*sortName : 'receiveDt',
        sortOrder : 'desc',*/
        checkOnSelect : true,//单击选中
        emptyMsg : "暂无数据",
        selectOnCheck : true,
        rownumbers:true,
        frozenColumns:[[{
            field:'id',
            checkbox : true
        }]],
        columns:[[
            {
                field : 'name',
                title : '计划名称',
                width:'10%',
                formatter:function (value,row,index) {
                    return "<a name='detail' href='javascript:;' row='"+index+"'>"+value+"</a>"
                }
            },{
            field : 'logisticsName',
            title : '国际物流产品',
            width:'10%'
        },{
            field:'channelName',
            title:'国际物流路线名称',
            width:'10%'
        },{
            field:'toWarehouseName',
            title:'海外仓',
            width:'12%'
        },{
            field:'actualCarrier',
            title:'实际承运人',
            width:'10%'
        },{
            field:'voyageNo',
            title:'船名/航次',
            width:'10%'
        },{
            field:'startPort',
            title:'起运港',
            width:'10%'
        },{
            field:'destPort',
            title:'目的港',
            width:'10%'
        },{
            field:'estimateLeaveDt',
            title:'预计离港时间'
        },{
            field:'estimateArriveDt',
            title:'预计到达时间'
        },{
            field:'tLastOrderDt',
            title:'截单时间'
        },{
            field:'tLastCollectDt',
            title:'截货时间'
        },{
            field:'lastOrderDt',
            title:'下入库单最迟时间'
        },{
            field:'lastCollectDt',
            title:'企业送货最迟时间'
        },{
            field:'memo',
            title:'备注'
        },{
            field:'opt',
            title:'操作',
            hidden:isSale,
            formatter:function (value,row,index) {
                return "<a name='edit' href='javascript:;' row='"+index+"'>修改</a>|" +
                    "<a href='javascript:;' name='delete' row='"+index+"'>删除</a>"
            }
        }]],
        loadFilter:function(data){
            if(data.code!='200'){
                alert(data.message);
                return data.data;
            }
            return data.data;
        },
        onClickRow:function (index,data) {
            var $row = $("#datagrid-row-r1-1-"+index).find("input[type=checkbox]");
            if(!$row.prop("checked")){
                $(this).datagrid('unselectRow', index);
            }else{
                $(this).datagrid('selectRow', index);
            }
        },
        onLoadSuccess:function(data){
            $("#logistics_Plan_table").datagrid('clearSelections');
        },
        toolbar:"#tb"
    });
    $("#ft").show();
}

// ajax 操作 url data-发送的数据
function optFun(url,data) {
    $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:'json',
        success:function (result) {
            if(result.code == 200){

            }else{
                alert(result.message);
            }
            $('#logistics_Plan_table').datagrid('reload');
        },
        error:function (e) {
            console.error("接口url:"+url+" 请求失败");
        }
    })
}
//组装id
function installId(selectRow) {
    var jsonString = [];
    $.each(selectRow,function (index,obj) {
        jsonString[index] = {"id":obj.id};
    })
    return jsonString;
}

//upload初始化
function uploadinit() {
    $("#uploadifive").uploadifive(
        $.extend({},uploadifiveSettings,{
            uploadScript: 'api/v1/p/mms/logisticsChannelPlan/import',
            onUploadComplete : function(file, data) {
                var obj = JSON.parse(data);
                if(obj.code == 201){
                    console.info(data.message);
                    window.open("api/v1/p/crm/fileoper/download?id="+obj.data.id);
                }else if(obj.code ==200){

                }else{
                    alert(obj.message);
                }
            }
        })
    )
}
//添加参数
function appendOption(url,data,$select) {
    $.ajax({
        url:url,
        type:'post',
        data:data,
        dataType:'json',
        success:function (result) {
            if(result.code==200){
                $select.combobox({
                    data:result.data,
                    valueField:'id',
                    textField:'name'
                });
            }else{
                console.error(result.message);
            }
        },
        error:function (e) {
            console.log('接口错误');
        }
    })
}
function comboxInit(url,data,$select) {
    $select.combobox({
        url:url,
        valueField:'id',
        textField:'name',
        queryParams:data,
        loadFilter:function(result){
            if(result.code=='200'){
                result.data.unshift({id:'',name:'全部'});
                return result.data;
            }
        }
    })
}
function destInit() {
    $("#toWarehouseId").combobox({
        url:'api/v1/p/crm/warehouse/query',
        valueField:'warehouseId',
        textField:'warehouseName',
        queryParams:{
            warehouseType:'DEST'
        },
        loadFilter:function(result){
            if(result.code=='200'){
                result.data.unshift({warehouseId:'',warehouseName:'全部'});
                return result.data;
            }
        }
    })
}